package cn.crex1.xiaomi.core.orm.transaction.support;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.crex1.xiaomi.core.orm.transaction.TransactionManager;

public class JdbcTransactionManager implements TransactionManager{
	
	private Logger logger =LoggerFactory.getLogger(JdbcTransactionManager.class);
	
	/**
	 * 通过连接对象打开事务
	 */
	@Override
	public void openTransaction(Connection connection){
		try {
			if (connection!=null && connection.getAutoCommit()) {
				connection.setAutoCommit(false);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 通过连接对象提交事务
	 */
	@Override
	public void commitTransaction(Connection connection) {
		try {
			if (connection!=null && !connection.getAutoCommit()) {
				connection.commit();
			}
		} catch (SQLException e) {
			rollbackTransaction(connection);
			e.printStackTrace();
		}
	}
	/**
	 * 通过连接的对象回滚事务
	 */
	@Override
	public void rollbackTransaction(Connection connection) {
		try {
			if (connection!=null && !connection.getAutoCommit()) {
				logger.error("rollback a transaction");
				connection.rollback();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 通过连接对象关闭事务
	 */
	@Override
	public void closeTransaction(Connection connection) {
		try {
			if (connection!=null && !connection.getAutoCommit()) {
				connection.setAutoCommit(true);
//				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
